﻿using System;
using System.Data.Services;
using System.Linq.Expressions;

namespace AstoriaPlus.Extensions
{
	internal class QueryInterceptors<TDataService, TDataSource>
		where TDataService : DataService<TDataSource>
		where TDataSource : class
	{
		private readonly ExtendedDataServiceConfiguration<TDataService, TDataSource> configuration;

		public QueryInterceptors(ExtendedDataServiceConfiguration<TDataService, TDataSource> configuration)
		{
			this.configuration = configuration;
		}

		public Expression<Func<TEntity, bool>> For<TEntity>(DataServiceQueryContext<TDataService, TDataSource> context)
			where TEntity : class
		{
			var expression = this.GetExpression<TEntity>();
			if (expression == null)
			{
				return e => true;
			}

			return QueryEvaluator<TEntity, DataServiceQueryContext<TDataService, TDataSource>>.Eval(expression, context);
		}

		private Expression<Func<TEntity, DataServiceQueryContext<TDataService, TDataSource>, bool>> GetExpression<TEntity>()
		{
			Expression expression;
			if (this.configuration.QueryInterceptors.TryGetValue(typeof(TEntity), out expression))
			{
				return (Expression<Func<TEntity, DataServiceQueryContext<TDataService, TDataSource>, bool>>)expression;
			}

			return null;
		}
	}
}
